from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render
from django.urls import reverse

from .form import TopicForm, EntryForm
from .models import Topic, Entry


# Create your views here.

def index(request):
    '''学习笔记主页'''
    return render(request, 'learning_logs/index.html')

## 当用户登录未登录会自动跳转到登录界面
@login_required
def topics(request):
    '''显示所有主题'''
    topics=Topic.objects.filter(owner=request.user).order_by('data_added')
    context={'topics':topics}
    return render(request,'learning_logs/topics.html',context)


def topic(request, topic_id):
    topic=Topic.objects.get(id=topic_id)
    if topic.owner !=request.user:
        raise Http404
    entries=topic.entry_set.order_by('-date_added')            ## 对topic条目进行降序排序
    context={ 'topic':topic, 'entries':entries }
    return render(request, 'learning_logs/topic.html',context)



@login_required
def new_topic(request):
    '''添加新主题'''
    if request.method != 'POST':
        form = TopicForm
    else:
        form = TopicForm(request.POST)
        ## 检查数据的合法性
        if form.is_valid():
            # form.save()

            ### 将数据存放到new_topic中
            new_topic=form.save(commit=False)
            new_topic.owner=request.user
            new_topic.save()


            return HttpResponseRedirect(reverse('learning_logs:topics'))

    context={'form':form}
    return render(request,'learning_logs/new_topic.html',context)



### 添加topic 实例
def new_entry(request,topic_id):
    topic=Topic.objects.get(id=topic_id)
    if request.method != 'POST':
        form = EntryForm()
    else:
        form = EntryForm(data=request.POST)
        if form.is_valid():
            new_entry=form.save(commit=False)
            new_entry.topic=topic
            new_entry.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id]))

    context={'topic':topic,'form':form}

    return render(request,'learning_logs/new_entry.html',context)



### 编辑实例
def edit_entry(request,entry_id):
    entry=Entry.objects.get(id=entry_id)
    topic=entry.topic
    if request.method!='POST':
        form = EntryForm(instance=entry)    ## 将实例装入表格中
    else:
        form=EntryForm(instance=entry,data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id]))
    context={'entry':entry,'topic':topic,'form':form}
    return render(request,'learning_logs/edit_entry.html',context)


